//
//  OpenSocialObjCClientLibraryAppDelegate.m
//  OpenSocialObjCClientLibrary
//
//  Created by Cassie Doll on 1/14/09.
//  Copyright Google 2009. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

#import "OpenSocialObjCClientLibraryAppDelegate.h"
#import "ProviderListController.h"
#import "OAServiceTicket.h"
#import "OpenSocialConsumer.h"
#import "OpenSocialProvider.h"
#import "NSDictionary_JSONExtensions.h"

@interface OpenSocialObjCClientLibraryAppDelegate ()
@property (nonatomic, retain) OpenSocialConsumer *consumer;
@property (nonatomic, retain) UILabel *label;

- (void)getPeople;
- (void)clearAuth;
@end

@implementation OpenSocialObjCClientLibraryAppDelegate

@synthesize consumer, label, window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {  
  NSMutableArray *providers = [NSMutableArray arrayWithCapacity:2];
  [providers addObject:[OpenSocialProvider getPlaxoProviderWithKey:@"anonymous" withSecret:@""]];  
  self.consumer = [[[OpenSocialConsumer alloc] initWithProviders:providers
                                               andCallbackScheme:@"opensocial-demo-library" 
                                                   andMainWindow:window] autorelease];
  
  self.label = [[[UILabel alloc] initWithFrame:CGRectMake(20, 40, 280, 340)] autorelease];
  [label setText:@"Click the fetch friends button to get all of your data."];
  [label setNumberOfLines:0];
  [window addSubview:label];
  
  UIButton *getFriendsButton = [[UIButton alloc] initWithFrame:CGRectMake(40, 423, 118, 37)];
  [getFriendsButton setTitle:@"Fetch friends" forState:UIControlStateNormal];
  [getFriendsButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
  [getFriendsButton addTarget:self action:@selector(getPeople) forControlEvents:UIControlEventTouchDown];
  [window addSubview:getFriendsButton];
  [getFriendsButton release];  
  
  UIButton *clearAuthButton = [[UIButton alloc] initWithFrame:CGRectMake(160, 423, 118, 37)];
  [clearAuthButton setTitle:@"Clear friends" forState:UIControlStateNormal];
  [clearAuthButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
  [clearAuthButton addTarget:self action:@selector(clearAuth) forControlEvents:UIControlEventTouchDown];
  [window addSubview:clearAuthButton];
  [clearAuthButton release];  
  
  [window makeKeyAndVisible];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
  // We have been called back by a successful OAuth token grant
  // Now we need to fetch the access token
  NSLog(@"Got handleOpenURL");
  [consumer finishAuthProcess];
  [self getPeople];
  return YES;
}

- (void)getPeople {
  NSString *url = @"/people/@me/@friends";
  if (![[consumer currentProvider] isOpenSocial]) {
    url = @"/@me/@all";
  }
  [consumer getDataForUrl:url 
            andParameters:nil 
                 delegate:self 
        didFinishSelector:@selector(peopleCallback:didFinishWithResponse:)];
}

- (void)clearAuth {
  [consumer clearAuthentication];  
}

- (void)peopleCallback:(OAServiceTicket *)ticket didFinishWithResponse:(id)response {
  if (ticket.didSucceed) {
    NSError *jsonParsingError = nil;
    NSDictionary * jsonPeople = [NSDictionary dictionaryWithJSONData:
                                 [response dataUsingEncoding:NSUTF8StringEncoding] error:&jsonParsingError];
    
    NSNumber *totalFriends = [jsonPeople objectForKey:@"totalResults"];
    NSString *labelText = [NSString stringWithFormat:@"You have %@ friend%@:\n", totalFriends, 
                          [totalFriends intValue] == 1 ? @"" : @"s"];
    
    NSArray *allFriends = [jsonPeople objectForKey:@"entry"];
    
    for (NSDictionary *friend in allFriends) {
      NSString *displayName = [friend objectForKey:@"displayName"];  
      labelText = [labelText stringByAppendingString:[NSString stringWithFormat:@"%@\n", displayName]];
    }
    
    [label setText:labelText];
  } else {
    NSLog(@"Got error while requesting people. %@", response);
  }
}

- (void)dealloc {
  [window release];
  [consumer release];
  [label release];
  [super dealloc];
}

@end

